<?php
/**
 * Magento Enterprise Edition
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Magento Enterprise Edition End User License Agreement
 * that is bundled with this package in the file LICENSE_EE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.magento.com/license/enterprise-edition
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magento.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Magento to newer
 * versions in the future. If you wish to customize Magento for your
 * needs please refer to http://www.magento.com for more information.
 *
 * @category    Mage
 * @package     Mage_Adminhtml
 * @copyright Copyright (c) 2006-2015 X.commerce, Inc. (http://www.magento.com)
 * @license http://www.magento.com/license/enterprise-edition
 */

/**
 * Adminhtml sales orders controller
 *
 * @category    Mage
 * @package     Mage_Adminhtml
 * @author      Magento Core Team <core@magentocommerce.com>
 */
require "Mage/Adminhtml/controllers/Sales/OrderController.php";
class Silk_Zgb_Adminhtml_OrderController extends Mage_Adminhtml_Sales_OrderController
{
    const STATE_PENDING = "pending";

    /**
     * Orders grid
     */
    public function indexAction()
    {
        $this->_title($this->__('Sales'))->_title($this->__('Orders'));

        $this->_initAction()
            ->renderLayout();
    }


    /**
     * Initialize shipment model instance
     *
     * @return Mage_Sales_Model_Order_Shipment|bool
     */
    protected function _initShipment($order)
    {
        // $order      = Mage::getModel('sales/order')->load($orderId);
        /**
         * Check order existing
         */
        if (!$order->getId()) {
            $this->_getSession()->addError($this->__('The order no longer exists.'));
            return false;
        }
        /**
         * Check shipment is available to create separate from invoice
         */
        if ($order->getForcedDoShipmentWithInvoice()) {
            $this->_getSession()->addError($this->__('Cannot do shipment for the order separately from invoice.'));
            return false;
        }
        /**
         * Check shipment create availability
         */
        if (!$order->canShip()) {
            $this->_getSession()->addError($this->__('Cannot do shipment for the order.'));
            return false;
        }
        // $savedQtys = $this->_getItemQtys();
        $savedQtys = array();
        $shipment = Mage::getModel('sales/service_order', $order)->prepareShipment($savedQtys);

        $tracks = $this->getRequest()->getPost('tracking');
        if ($tracks) {
            foreach ($tracks as $data) {
                if (empty($data['number'])) {
                    Mage::throwException($this->__('Tracking number cannot be empty.'));
                }
                $track = Mage::getModel('sales/order_shipment_track')
                    ->addData($data);
                $shipment->addTrack($track);
            }
        }

        // Mage::register('current_shipment', $shipment);
        return $shipment;
    }

    /**
     * Save shipment and order in one transaction
     *
     * @param Mage_Sales_Model_Order_Shipment $shipment
     * @return Mage_Adminhtml_Sales_Order_ShipmentController
     */
    protected function _saveShipment($shipment)
    {
        $shipment->getOrder()->setIsInProcess(true);
        $transactionSave = Mage::getModel('core/resource_transaction')
            ->addObject($shipment)
            ->addObject($shipment->getOrder())
            ->save();

        return $this;
    }

    public function shippingAction()
    {
        $orderIds = $this->getRequest()->getPost('order_ids');
        $cid = array();
        $errors = array();
        foreach($orderIds as $id)
        {
            $order = Mage::getModel('sales/order')->load($id);
            if ($order->getState() == "processing")
            {
				
		
            	
            	$shipment 	= $this->_initShipment($order);
            	$shipment->register();
            	$this->_saveShipment($shipment);
            	$order->setStatus('complete_delivering')->addStatusToHistory('complete_delivering','发货中')->save();
            	$cid[] 		= $order->getIncrementId();
 
            	
                //$cid[] = $order->getIncrementId();
            }
            else
            {
                $errors[] = $order->getIncrementId();
            }
        }

        if(count($cid)==count($orderIds))
        {
            $this->_getSession()->addSuccess("发货完成！");
        }
        else
        {
            $this->_getSession()->addError(implode(',', $errors)."发货失败！");
        }
        $this->_redirect('*/*/');
    }

    /**
     * Initialize invoice model instance
     *
     * @return Mage_Sales_Model_Order_Invoice
     */
    protected function _initInvoice($order, $update = false)
    {
        $invoice = false;
        $itemsToInvoice = 0;
        // $order = Mage::getModel('sales/order')->load($orderId);
        /**
         * Check order existing
         */
        if (!$order->getId()) {
            $this->_getSession()->addError($this->__('The order no longer exists.'));
            return false;
        }
        /**
         * Check invoice create availability
         */
        if (!$order->canInvoice()) {
            $this->_getSession()->addError($this->__('The order does not allow creating an invoice.'));
            return false;
        }
        // $savedQtys = $this->_getItemQtys();
        $savedQtys = array();
        $invoice = Mage::getModel('sales/service_order', $order)->prepareInvoice($savedQtys);
        if (!$invoice->getTotalQty()) {
            Mage::throwException($this->__('Cannot create an invoice without products.'));
        }

        // Mage::register('current_invoice', $invoice);
        return $invoice;
    }

    /**
     * Save data for invoice and related order
     *
     * @param   Mage_Sales_Model_Order_Invoice $invoice
     * @return  Mage_Adminhtml_Sales_Order_InvoiceController
     */
    protected function _saveInvoice($invoice)
    {
        $invoice->getOrder()->setIsInProcess(true);
        $transactionSave = Mage::getModel('core/resource_transaction')
            ->addObject($invoice)
            ->addObject($invoice->getOrder())
            ->save();
        return $this;
    }

    public function completeAction()
    {
        $orderIds = $this->getRequest()->getPost('order_ids');
        foreach($orderIds as $id)
        {
            $order = Mage::getModel('sales/order')->load($id);
            if($order->getStatus() == "processing")
            {
                $invoice = $this->_initInvoice($order);
                //var_dump($invoice);
                if($invoice)
                {
                    $invoice->register();
                    $invoice->setEmailSent(false);
                    $invoice->getOrder()->setIsInProcess(true);
                    $transactionSave = Mage::getModel('core/resource_transaction')
                        ->addObject($invoice)
                        ->addObject($invoice->getOrder());
                    $transactionSave->save();
                }
            }
        }
        $this->_getSession()->addSuccess("订单完成！");
        $this->_redirect('*/*/');
    }

    protected function getOrderstate($orderIds)
    {
        if($orderIds)
        {
            $orders = Mage::getModel('sales/order')->getCollection()
                ->addFieldToFilter('entity_id', array('in'=>$orderIds))
                ->addFieldToFilter('shipping_id', array('eq'=>0));

            if(count($orderIds) !== count($orders))
            {
                return false;
            }

            $allowedStatus = array(
                self::STATE_PENDING,
                Mage_Sales_Model_Order::STATE_PROCESSING,
            );
            $orderWebsiteIds = array();
            /** @var Mage_Sales_Model_Order $order */
            foreach($orders as $order)
            {
                if (!in_array($order->getStatus(), $allowedStatus))
                {
                    return false;
                }

                $orderWebsiteIds[$order->getStore()->getWebsiteId()] = true;
            }

            if (count($orderWebsiteIds) != 1) {
                return 500;
            }

            return true;
        }else{
            return false;
        }
    }

    public function newshippingAction()
    {
        $orderIds = $this->getRequest()->getPost('order_ids');
        $canShipping = $this->getOrderstate($orderIds);
        if (!$canShipping)
        {
            Mage::getSingleton("adminhtml/session")->addError(Mage::helper("adminhtml")->__("选择的订单中有订单状态不正确或已经加入到运单！"));
            return $this->_redirect('*/*/');
        } elseif ($canShipping === 500) {
            Mage::getSingleton("adminhtml/session")->addError(Mage::helper("adminhtml")->__("选择的订单不在同一站点下！"));
            return $this->_redirect('*/*/');
        }

        $this->loadLayout();
        $this->renderLayout();
    }

    public function addshippingAction()
    {

        $orderIds = $this->getRequest()->getParam('order_ids');
//add by wanglin start 异常区订单加入运单只显示分拣完成
        $addflag = $this->getRequest()->getParam('canshu');
//add by wanglin end  异常区订单加入运单只显示分配完成
        if (!is_array($orderIds)) {
            $orderIds = array((int)$orderIds);
        }
        $canShipping = $this->getOrderstate($orderIds);
        if (!$canShipping)
        {
            Mage::getSingleton("adminhtml/session")->addError(Mage::helper("adminhtml")->__("选择的订单中有订单状态不正确或已经加入到运单！"));
            return $this->_redirect('*/*/');
        } elseif ($canShipping === 500) {
            Mage::getSingleton("adminhtml/session")->addError(Mage::helper("adminhtml")->__("选择的订单不在同一站点下！"));
            return $this->_redirect('*/*/');
        }
        Mage::getSingleton("core/session")->setData("add_orderids",$orderIds);
        Mage::getSingleton("adminhtml/session")->addSuccess(Mage::helper("adminhtml")->__("挑拣订单成功，请选择运单并加入"));
        //add by wanglin 异常区订单加入运单只显示分拣完成
        $this->_redirect('tms/adminhtml_shipping/index',array('orderId'=>$orderIds[0],'addflag'=>$addflag));
        //add by end
        //$this->_redirect('tms/adminhtml_shipping/index',array('orderId'=>$orderIds[0]));
    }

    public function printAction()
    {
        $session = Mage::getSingleton('admin/session');
        $user = $session->getUser();
        $websiteId = $user->getWebsiteId();
        $store = Mage::getModel('core/store');
        if($websiteId)
        {
            $website = new Mage_Core_Model_Website();
            $website->load($websiteId);
            $store = $website->getDefaultStore();
        }


        $orderIds = $this->getRequest()->getPost('order_ids');
        $_coreHelper = Mage::helper('core');
        $collection = Mage::getModel('sales/order')->getCollection()
            ->addFieldToSelect(array('entity_id','customer_id'))
            ->addFieldToFilter('status', array('neq'=>'canceled'))
            ->addFieldToFilter('entity_id', array('in'=>$orderIds));

        foreach($collection as $item)
        {
            $order = Mage::getModel('sales/order')->load($item->getId());
            if($order->getState()=='processing') continue;
            if($order->getState()=='canceled') continue;
            if($order->getState()=='closed') continue;
            if(!$order->canInvoice()) continue;
            $invoice = $this->_initInvoice($order);
            if($invoice)
            {
                $invoice->register();
                $invoice->setEmailSent(false);
                $invoice->getOrder()->setIsInProcess(true);
                $transactionSave = Mage::getModel('core/resource_transaction')
                    ->addObject($invoice)
                    ->addObject($invoice->getOrder()->addStatusToHistory('processing','打印出库单'));
                $transactionSave->save();
            }
        }

        $this->loadLayout();
        $this->renderLayout();
    }

    /**
     *  Save invoice for order
     *
     *  @param    Mage_Sales_Model_Order $order
     *  @return      boolean Can save invoice or not
     */
    protected function saveInvoiceForOrder(Mage_Sales_Model_Order $order)
    {
        if ($order->canInvoice())
        {
            $convertor = Mage::getModel('sales/convert_order');
            $invoice = $convertor->toInvoice($order);
            foreach ($order->getAllItems() as $orderItem)
            {
                if (!$orderItem->getQtyToInvoice())
                {
                    continue ;
                }
                $item = $convertor->itemToInvoiceItem($orderItem);
                $item->setQty($orderItem->getQtyToInvoice());
                $invoice->addItem($item);
            }
            $invoice->collectTotals();
            $invoice->register()->capture();
            Mage::getModel('core/resource_transaction')
            ->addObject($invoice)
            ->addObject($invoice->getOrder())
            ->save();
            return true;
        }

        return false;
    }

    public function printPickingAction()
    {
        $this->loadLayout();
        $this->renderLayout();
    }

    /* rewrite for salse_order/addCommentAction to order_complete */
    public function addCommentAction()
    {
        if ($order = $this->_initOrder()) {
            try {
                $response = false;
                $data = $this->getRequest()->getPost('history');
                $notify = isset($data['is_customer_notified']) ? $data['is_customer_notified'] : false;
                $visible = isset($data['is_visible_on_front']) ? $data['is_visible_on_front'] : false;

                $order->addStatusHistoryComment($data['comment'], $data['status'])
                    ->setIsVisibleOnFront($visible)
                    ->setIsCustomerNotified($notify);

                $comment = trim(strip_tags($data['comment']));

                $order->save();
                $order->sendOrderUpdateEmail($notify, $comment);

                /*Set tms_shipping_order status*/
                $orderId = $order->getId();
                $dbwrite = Mage::getSingleton('core/resource')->getConnection('core_write');
                if($data['status'] == 'order_complete')
                {
                    $sqlStr = "UPDATE tms_shipping_order SET status = 'order_complete' WHERE order_id = {$orderId}";
                    $dbwrite->query($sqlStr);
                }

                $this->loadLayout('empty');
                $this->renderLayout();
            }
            catch (Mage_Core_Exception $e) {
                $response = array(
                    'error'     => true,
                    'message'   => $e->getMessage(),
                );
            }
            catch (Exception $e) {
                $response = array(
                    'error'     => true,
                    'message'   => $this->__('Cannot add order history.')
                );
            }
            if (is_array($response)) {
                $response = Mage::helper('core')->jsonEncode($response);
                $this->getResponse()->setBody($response);
            }
        }
    }

    /*Order Complete*/
    // public function ordercompleteAction()
    // {
    //     $orderIds = $this->getRequest()->getPost('order_ids');

    //     $data['comment'] = '';
    //     $data['status']  = 'order_complete';

    //     foreach($orderIds as $id)
    //     {
    //         $order = Mage::getModel('sales/order')->load($id);
    //         $sucessStr = "";
    //         if($order->getStatus() == 'complete')
    //         {
    //             $order->addStatusHistoryComment($data['comment'], $data['status']);
    //             $comment = trim(strip_tags($data['comment']));

    //             if($order->save())
    //             {
    //                 $order->sendOrderUpdateEmail($notify, $comment);
    //                 $this->changeShippingOrderStatus($id);
    //                 $sucessStr += '|' . $order->getId() . '|';
    //             }
    //         }else{
    //             $errotStr += '|' . $order->getId() . '|';
    //             continue;
    //         }
    //     }

    //     if($errotStr && !$sucessStr)
    //     {
    //         $this->_getSession()->addError("选择订单中存在不具备[完成订单]操作条件的订单！");
    //     }elseif(!$errotStr && $sucessStr)
    //     {
    //         $this->_getSession()->addSuccess("订单[完成订单]成功！");
    //     }else{
    //         //$this->_getSession()->addError("选择订单中存在不具备[完成订单]操作条件的订单！已经排除");
    //         $this->_getSession()->addSuccess("订单[完成订单]成功！");
    //     }

    //     $this->_redirect('*/*/');
    // }

    public function completeOrderAction()
    {
        $orderId = $this->getRequest()->getParam('order_id');
        $orderIds = $this->getRequest()->getPost('order_ids');

        if(!$orderIds)
        {
            $orderIds = array();
            $orderIds[] = $orderId;
        }

        foreach($orderIds as $oid)
        {
            $order = Mage::getModel('sales/order')->load($oid);
            if($order->getState()=='complete' && $order->getStatus()!='complete_order')
            {
                $memoError = false;
                $memos = Mage::getModel('sales/order_creditmemo')
                    ->getCollection()
                    ->addFieldToSelect('*')
                    ->addFieldToFilter('order_id', array('eq'=>$order->getId()));

                foreach($memos as $memo)
                {
                    if($memo->getState()==Mage_Sales_Model_Order_Creditmemo::STATE_CANCELED) continue;
                    if($memo->getState()!=Mage_Sales_Model_Order_Creditmemo::STATE_REFUNDED)
                    {
                        $this->_getSession()->addError("{$order->getIncrementId()}有尚未完成的退款/退货单!");
                        $memoError = true;
                    }
                }
                if($memoError) continue;
                
 
            	$order->setStatus("complete_order")->addStatusToHistory('complete_order','确认收款');
            		$shipOrder = Mage::getModel('tms/shipping_order')->load($order->getIncrementId(),'increment_id');
            		$shipOrder->setStatus('complete_order');
            		$transactionSave = Mage::getModel('core/resource_transaction')
            		->addObject($order)
            		->addObject($shipOrder)
            		->save();
				//add by wanglin start 确认收款增加金额到K3
            		$add_bill = $order->getGrandTotal()-$order->getSubtotalRefunded();
            		$dbwrite = Mage::getSingleton('core/resource')->getConnection('core_write');
            		try {
            			$sqlStr = "UPDATE sales_flat_order_status_history SET add_bill = '".$add_bill."' WHERE parent_id = {$oid} AND entity_name='order' AND status='complete_order' AND comment='确认收款'";
            			$dbwrite->query($sqlStr);
            		}catch (Exception $e){
            			$this->_getSession()->addSuccess("{$order->getIncrementId()}收款确认成功！");
            		}
            	//add by wanglin end	
					
            		$this->_getSession()->addSuccess("{$order->getIncrementId()}收款确认成功！"); 
            }
            else
            {
                if($order->getState()!='complete')
                {
                    $this->_getSession()->addError("{$order->getIncrementId()}状态不在配送完成状态无法进行确认收款操作");
                }
                else
                {
                    if($order->getStatus()=='complete_order')
                    {
                        $this->_getSession()->addError("{$order->getIncrementId()}已经确认无需再次确认！");
                    }
                    else
                    {
                        $this->_getSession()->addError("{$order->getIncrementId()}状态不正确，无法确认收款！");
                    }
                    
                }
            }
        }

        if($orderId)
        {
            $this->_redirect('*/*/view',array('order_id'=>$orderId));
        }
        else
        {
            $this->_redirect('*/*/');
        } 
    }

    protected function changeShippingOrderStatus($orderId)
    {
        $db = Mage::getSingleton('core/resource')->getConnection('core_read');
        $sql= "SELECT * FROM tms_shipping_order WHERE order_id = {$orderId}";
        $query = $db->query($sql);
        
        if($query->fetchAll())
        {
            $dbwrite = Mage::getSingleton('core/resource')->getConnection('core_write');
            $sqlStr = "UPDATE tms_shipping_order SET status = 'order_complete' WHERE order_id = {$orderId}";
            $dbwrite->query($sqlStr);
        }
    }
}
